#!/usr/bin/env python3

import argparse
import gv.gvsoc_control as gvsoc

parser = argparse.ArgumentParser(description='Control GVSOC')

parser.add_argument("--host", dest="host", default="localhost", help="Specify host name")
parser.add_argument("--port", dest="port", default=42951, type=int, help="Specify host port")

args = parser.parse_args()


def wait_until_different(gv, value):
    while True:
        gv.run(1000000)
        address = axi.mem_read_int(0x1c000000, 4)
        if address != value:
            break


gv = gvsoc.Proxy(args.host, args.port)

axi = gvsoc.Router(gv)

# Wait 1ms to be sure the ROM has booted since we are writing at beginning of binary
gv.run(1000000000)

current_read_value = 0
current_write_value = 0
buffer_size = 64*1024
rx_status = None

# Send a value to the simulated test
axi.mem_write_int(0x1c000000, 4, 0x11223344)
wait_until_different(gv, 0x11223344)

for i in range(0, 10):

    wait_until_different(gv, 0x0)

    address = axi.mem_read_int(0x1c000000, 4)

    read_values = axi.mem_read(address, buffer_size)

    read_values_int = []
    for i in range(0, int(buffer_size/4)):
        read_values_int.append(int.from_bytes(read_values[i*4:i*4 + 4], byteorder="little", signed=False))

    for i in range(0, int(buffer_size/4)):
        if read_values_int[i] != current_read_value:
            rx_status = 'Error, expected 0x%x, got 0x%x' % (current_read_value, read_values[i])

        current_read_value += 11

    write_values = bytearray()
    for i in range(0, int(buffer_size/4)):
        write_values += int.to_bytes(current_write_value, 4, byteorder="little")
        current_write_value += 43

    axi.mem_write(address, buffer_size, write_values)
    axi.mem_write_int(0x1c000000, 4, 0)


gv.quit()
gv.close()
